package top.hcode.hoj.controller.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.hcode.hoj.annotation.AnonApi;
import top.hcode.hoj.common.result.CommonResult;
import top.hcode.hoj.pojo.dto.BaseIdDTO;
import top.hcode.hoj.pojo.dto.QuerySampleDTO;
import top.hcode.hoj.pojo.dto.TyOrgSyncDTO;
import top.hcode.hoj.pojo.entity.org.TyOrg;
import top.hcode.hoj.service.admin.AdminTyOrgService;

/**
 * @author orangej
 * @since 2025-01-22
 */
@Slf4j
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class AdminTyOrgController {

    private final AdminTyOrgService tyOrgService;

    @GetMapping("/admin/ty-org/list")
    public CommonResult<IPage<TyOrg>> getTyOrgList(QuerySampleDTO querySampleDTO) {
        return CommonResult.successResponse(tyOrgService.getTyOrgList(querySampleDTO));
    }

    @PostMapping("/admin/ty-org/save")
    public CommonResult<TyOrg> saveTyOrg(@RequestBody TyOrg tyOrg) {
        return CommonResult.successResponse(tyOrgService.saveTyOrg(tyOrg));
    }

    @PostMapping("/admin/ty-org/delete")
    public CommonResult<Void> deleteTyOrg(@RequestBody BaseIdDTO dto) {
        tyOrgService.deleteTyOrg(dto.getId());
        return CommonResult.successResponse();
    }

    @AnonApi
    @PostMapping("/admin/ty-org/sync-and-export")
    public CommonResult<String> syncAndExport(@RequestHeader("X-API-KEY") String apiKey, 
                                              @RequestBody TyOrgSyncDTO syncDTO) {
        // 验证API密钥
        if (!"hoj-ty-sync-2025".equals(apiKey)) {
            return CommonResult.errorResponse("API密钥验证失败", 401);
        }
        
        // 检查是否有同步任务正在进行
        if (tyOrgService.isSyncInProgress()) {
            return CommonResult.errorResponse("系统正在执行同步任务，请稍后再试");
        }
        
        // 异步执行同步和导出任务
        tyOrgService.asyncSyncAndExport(syncDTO);
        
        return CommonResult.successResponse("同步和导出任务已提交，正在后台处理中...");
    }

}
